Ext.define('Sencha.controller.DictionaryDetailController', {
    extend: 'Ext.app.Controller',

    config: {
        // properties
        //mediaPtr: null,
        
        refs: {
            main: 'dictionarysourcenavigationview',
            dictionaryDetailView: 'dictionarytargetdetailview',
            dictionaryEntryButton: 'button[id=dictionaryEntryButton]',
            dictionaryThumb: 'dictionarydetailpageview',
            dictionaryImageThumb: 'image[cls=dictionaryImageButton]',
            imageContainer: 'container[cls=imageContainer]'
            //dictionarySpeakerButton: 'image[cls=dictionarySpeakerButton]'
        },
        control: {
            'dictionaryDetailView' :{
           		initialize: 'onShowDictionaryDetailView',
                activeitemchange: 'onActiveItemChange',
                show: 'onDictionaryDetailViewShow'
            },
           'dictionaryImageThumb' : {
                tap: 'onDictionaryImageButtonTap'
            }/*,
           
           'dictionarySpeakerButton' : {
                tap: 'onDictionarySpeakerButtonTap'
            },
           'dictionaryDetailPageView' : {
                erase: 'onDictionaryDetailPageViewErase'
           }
           */
           
            /*,
            'editDictionaryEntryButton' :{
           		tap: 'editDictionary'
            }
            */
        }
    },

           
    // Utility function - sets visibility of the dictionaryEntryButton (in toolbar) based on 
    // current entries 'isEditable' flag
    //
    setDictionaryEntryButtonVisibility : function() {
        var curRecord = this.getDictionaryDetailView().getListView().getStore().getAt( this.getDictionaryDetailView().getCurrentListItem() );
           console.log('isEditable = ' + curRecord.get('isEditable') );
        if ( curRecord.get('isEditable')=='1' ){
           this.getDictionaryEntryButton().show();
           console.log('show edit button');
        } else {
           this.getDictionaryEntryButton().hide();
           console.log('DictionaryDetailController : hide edit button it');
        }
    },
           
           
    // on DictionaryDetailView show
    //
    onDictionaryDetailViewShow : function() {
        // show/hide dictionaryEntryButton
        this.setDictionaryEntryButtonVisibility();
    },
               
    // *** DELETE this and event handler if not required
    // Create edit button on initialize
    onShowDictionaryDetailView : function(carousel) {
        console.log("in onPainted!!!!!!!!");
        var activeItemIndex = null;
        var carouselSize = carousel.getCarouselSize();
        var carouselBufferSize = carousel.getCarouselBufferSize();   
        //var selectedItem = this.getDictionaryDetailView().getSelectedItem();   
        var listIndex = carousel.getSelectedItem() - carouselBufferSize; // minus two because we have two either side
            
           console.log('listIndex = ' + listIndex );
           console.log('selected item = ' + carousel.getSelectedItem() );
        var activeItemIndex = Math.floor(carouselSize/2); // defaults to the middle 
           console.log('activeItemIndex = ' + activeItemIndex );
        // if near start of list and carousel window goes beyond bounds, then start at 0
        if (listIndex<0) {
           listIndex = 0;
        }
           console.log('carouselSize = ' + carouselSize );
        // Populate carousel with up to 5 items
        for (i=0; i<carouselSize; i++) {
           var record = carousel.getListView().getStore().getAt(listIndex);
           console.log('i = ' + i);
           // if this record exists ie. within bounds of the list view
           
           if (record) {
                // if this is the item clicked on, remember it
                if (listIndex == carousel.getSelectedItem() ) {
           console.log('FOUND active item. listIndex = ' + listIndex);
                    activeItemIndex = i;
                    //this.getDictionaryDetailView().setActiveItem(i);
                    //this.getDictionaryDetailView().setActiveItemTemp(i); // store for later
                }
            
                // Add card to carousel including HTML content
           var newContainer = Ext.create('Sencha.view.DictionaryDetailPageView', {sourceRecord: record, navigationView: this.getMain() });
           console.log ('adding ' + record.get('sourceWord') );
                this.getDictionaryDetailView().add(newContainer);
           
                listIndex++;
           }
           // else no more records left in list
           else {
                break;
           }
        }
           
        // Store the currently active item - used for comparison later
        this.getDictionaryDetailView().setActiveItemTemp(activeItemIndex);
        // Set the active item ie. which card to show (Note: this trigger onActiveItemChange, see below)
           console.log("SETTING active item to " + activeItemIndex);
        this.getDictionaryDetailView().setActiveItem(activeItemIndex);
        console.log('...getActiveIndex()=' + this.getDictionaryDetailView().getActiveIndex() );
        // Set the list pointer - used to keep track of which item in the list is displayed in carousel
        this.getDictionaryDetailView().setCurrentListItem( this.getDictionaryDetailView().getSelectedItem() );
    },
    
           
    onActiveItemChange: function(carousel, newItem, oldItem) {
           console.log("in onACtiveItemChange ***** carousel.getActiveItemTemp()="+carousel.getActiveItemTemp() + "carousel.getActiveIndex()=" + carousel.getActiveIndex() );
           
        // activeItemchange event is over zealous. Captures not just card changes but also setActiveItem
        // and even when leaving the carousel returning to list view. So need to detect these cases 
        var innerItems = this.getMain().getInnerItems();
        var currentItem = innerItems[innerItems.length-1].xtype; 
        if (currentItem=="dictionarycontainerlist")
        {
            return;
        }
           
        // Do nothing if this has been triggered by setting active item during initialization or this is the first item added (which also triggers this event)
           console.log('carousel.getActiveItemTemp()=' + carousel.getActiveItemTemp() );
           console.log('carousel.getActiveIndex()=' + carousel.getActiveIndex() );
        if ( carousel.getActiveItemTemp()==carousel.getActiveIndex() || carousel.getInnerItems().length==1 ) {
           console.log("BUG OUT");
           return;
        }
           
        // Current item in carousel
        var currentCarouselItem = carousel.getActiveIndex(); 
           console.log('carousel active item = ' + carousel.getActiveIndex() );
        var lastCarouselItem = carousel.getInnerItems().length-1; // last item in carousel
           
        
        
        // if moving to the right
        if ( currentCarouselItem > carousel.getActiveItemTemp() ) {
           // if the buffer to the right is now less than the carousel buffer size
           console.log('moving to right');
           console.log('lastCarouselItem=' + lastCarouselItem + ' currentCarouselItem+carousel.getCarouselBufferSize()=' + (currentCarouselItem+carousel.getCarouselBufferSize()) );
           
           if (  ( currentCarouselItem+carousel.getCarouselBufferSize() ) > lastCarouselItem  ) {
           
           // Get next record out of carousel bounds
                var record = carousel.getListView().getStore().getAt( carousel.getCurrentListItem()+carousel.getCarouselBufferSize()+1 );
        
                // If there is a record ie. we haven't reached the end of the list
                if (record) {
           console.log ('thre is a record (ie. not at end of list. it is ' + record.get('sourceWord') );
                    var newContainer = Ext.create('Sencha.view.DictionaryDetailPageView', {sourceRecord: record});
                    carousel.add(newContainer);
           
                    // if there is at least the buffer size to the left
                    if ( currentCarouselItem > (carousel.getCarouselBufferSize()-1) ) {
                        // remove first item in window
           console.log('removing item...');
                        //carousel.removeAt(0);
                        carousel.getAt(0).remove();
                        //carousel.remove(carousel.getAt(0) , true);
           console.log('removed item');
                    }
                } else {
           console.log('no more records to add');
                }
           }
           
           // set current list pointer to the next item in the list
           carousel.setCurrentListItem( carousel.getCurrentListItem()+1 );
        }
        // else moving to the left
        else {
           console.log('moving left...');
           // if the buffer to the left is now less than the carousel buffer size 
           if (  ( currentCarouselItem-carousel.getCarouselBufferSize() ) < 0  ) {
           console.log('need to top up...');
                // get next record (to left) out of carousel bounds
                var record = carousel.getListView().getStore().getAt( carousel.getCurrentListItem()-(carousel.getCarouselBufferSize()+1) );
           
                // if there is a record
                if (record) {
           console.log('found record: ' + record.get('sourceWord') );
                    // add new item to start of carousel
                    var newContainer = Ext.create('Sencha.view.DictionaryDetailPageView', {sourceRecord: record});
           console.log('inserting newContainer');
                    //carousel.insert(0, newContainer);
           console.log('number of cards = ' + carousel.getItems().length );
           console.log('current item = ' + carousel.getActiveIndex() );
           this.getDictionaryDetailView().insert(0, newContainer);
                    carousel.setActiveItem( carousel.getActiveIndex()-1 );
                    //this.getDictionaryDetailViews().insert(0, newContainer);
           console.log('number of cards = ' + carousel.getItems().length );
           console.log('current item = ' + carousel.getActiveIndex() );
           //carousel.getInnerItems().unshift(newContainer);
           
           
                    // we've added an item to the start of the array, so we need to reset our variables
                    currentCarouselItem = carousel.getActiveIndex(); 
                    lastCarouselItem = carousel.getInnerItems().length-1;
                    // if there is at least the required buffer size to the right
                    if ( (lastCarouselItem-currentCarouselItem)>(carousel.getCarouselBufferSize()-1)  ) {
                        // remove item from end
                        //this.getDictionaryDetailView().removeInnerAt( lastCarouselItem );
                       console.log('remove item from the right');
                        carousel.getAt(lastCarouselItem).remove();
                    }
                }
           }
           
           // set current list pointer to the next item in the list
           carousel.setCurrentListItem( carousel.getCurrentListItem()-1 );
        }
           
        // store current active item for comparison next time
        carousel.setActiveItemTemp( carousel.getActiveIndex() );
           console.log('end of fn.');
           
        // Set dictionary entry button visibility
        this.setDictionaryEntryButtonVisibility();
    },    
           
           
    // Show full screen view of image in new container
    //
    onDictionaryImageButtonTap : function() {
        console.log ('in on onDictionaryImageButtonTap...');
           
        this.getDictionaryEntryButton().hide(); // hide edit button - we don't want to edit from image
        this.getMain().getLayout().setAnimation('flip'); // set animation
        
        var curRecord = this.getDictionaryDetailView().getListView().getStore().getAt( this.getDictionaryDetailView().getCurrentListItem() );
        var associatedRecord = Ext.getStore("DictionaryTargets").getById( curRecord.get('dictionaryTargetId') );   
        
        var newImageView = Ext.create('Sencha.view.ImageView');
        this.getMain().add(newImageView);
        this.getImageContainer().setHtml('<div class=dictImage><img src="' + Sencha.app.getPersistentFileStoreVar() + '/assets/' + associatedRecord.get('imageURL') + '" /></div>');
    
    },
           
           
    //showing edit form for dictionary
   	editDictionary : function(){
        console.log("editDictionary...");
        
        //var bar = this.getMain().getNavigationBar();
        //this.getNewDictionaryButton().hide();
        this.getEditDictionaryEntryButton().setText('DONE');
        
        /*
        bar.add({
            xtype   : 'button',
            text    : 'EDIT',
            id      : 'editDictionaryButton',
            align 	: 'right',
            cls		: 'editDictionaryButton'
        });
        */
        
    	this.getMain().push({
    		title: 'Second',
    		xtype: 'dictionaryformview'			                    
        });
   	}
});
